module seek_module

contains

  integer*4 function rb_seek(itype,TargetID)
    use logs
    use header
    use hsmlfile
    use particles
    implicit none
    integer*4 :: HotIndex,i1,i2,itrip,TargetID,itype

    i1 = 1
    i2 = NumPart_Total(itype)
    HotIndex = i2/2
    itrip = 0

    do
       if(HotIndex == i1 .AND. itrip == 0) then
          itrip = 1
       else if(HotIndex == i1 .AND. itrip == 1) then
          HotIndex = HotIndex + 1
          itrip = 2
       else if(HotIndex == i1 .AND. itrip == 2) then
          write(*,*)itype,TargetID,hsml%ParticleIDs(1)
          call abort(' -rb_seek unable to find TargetID')
          stop
       endif
       
       if(TargetID > hsml%ParticleIDs(HotIndex)) then
          i1= HotIndex
          HotIndex = i1 + (i2-i1)/2
       else if(TargetID < hsml%ParticleIDs(HotIndex)) then
          i2 = HotIndex
          HotIndex = i1 + (i2-i1)/2
       else
          rb_seek = HotIndex
          exit
       endif
    enddo
    
    return
  end function rb_seek


end module seek_module
